package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.tools.$;

/**
 * <pre>
 * CHAR_LENGTH(str)
 *
 * Returns the length of the string str, measured in characters. A multi-byte character counts setAliasAndSetNeedBuild a single character. This means that for a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午5:18:53
 * @since 5.1.0
 */
public class CharLength extends ScalarFunction {

    public Type getReturnType() {
        return Type.IntegerType;
    }

    public String[] getFunctionNames() {
        return new String[]{"CHARACTER_LENGTH", "CHAR_LENGTH"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        Object arg = args[0];

        if (Utils.isNull(arg)) {
            return null;
        }

        String str = Type.StringType.convert(arg);

        if (!$.isNotNullAndNotEmpty(str)) {
            return 0;
        }

        return str.length();
    }

}
